package com.hefei.garden.config.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hefei.garden.dto.response.ResultVo;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author: devil
 * @Date: 2022/7/21 20
 * @Description: controller 返回层包装
 */
@RestControllerAdvice(basePackages = {"com.hefei.garden"})
public class ControllerResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 如果你的controller返回值是ResultVo，跳过不处理
        boolean flag1 = methodParameter.getParameterType().isAssignableFrom(ResultVo.class);
        // 如果的你的controller的方法上有NotControllerResponseAdvice注解，跳过不处理
        boolean flag2 = methodParameter.hasMethodAnnotation(NotControllerResponseAdvice.class);
        return !(flag1 || flag2);
    }

    @Override
    public Object beforeBodyWrite(Object data,
                                  MethodParameter returnType,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                return objectMapper.writeValueAsString(new ResultVo(data));
            } catch (JsonProcessingException e) {
                throw new RuntimeException("ControllerResponseAdvice Error...");
            }
        }
        return new ResultVo(data);
    }
}
